package com.sky.schedule;

import cn.hutool.core.collection.CollUtil;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class OrderTask {
    private final OrderMapper orderMapper;

    /**
     * 支付超时订单处理
     */
//    @Scheduled(cron = "0 0/1 * * * ?")
    @XxlJob("processTimeOutOrder")
    public void processTimeOutOrder() {
        log.info("开始处理超时订单-{}", LocalDateTime.now());
        //获取所有待付款订单
        List<Orders> ordersList = orderMapper.getAllOrders(Orders.PENDING_PAYMENT, LocalDateTime.now().minusMinutes(15));
        if (CollUtil.isNotEmpty(ordersList)) {
            // 批量更新订单状态
            List<Long> idList = ordersList.stream().map(Orders::getId).collect(Collectors.toList());
            orderMapper.updateBatch(Orders.CANCELLED, "订单超时未支付，自动取消订单", LocalDateTime.now(), idList);
        } else {
            log.info("没有待付款超时订单");
        }

    }

    /**
     * 派送中状态订单的处理(超过一个小时还在派送中的订单为已完成)
     */
//    @Scheduled(cron = "0 0 1 * * ?")
    @XxlJob("processDeliveryOrder")
    public void processDeliveryOrder() {
        log.info("派送中状态订单的处理-{}", LocalDateTime.now());
        //获取所有派送中的订单
        List<Orders> ordersList = orderMapper.getAllOrders(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().minusMinutes(60));
        if (CollUtil.isNotEmpty(ordersList)) {
            List<Long> idList = ordersList.stream().map(Orders::getId).collect(Collectors.toList());
            orderMapper.updateBatch(Orders.COMPLETED, "", null, idList);
        } else {
            log.info("没有派送中状态超时订单");
        }
    }
}

